package org.dao.manager;

import java.util.HashMap;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class EntityManagerHolder {
	
	private static HashMap<String, EntityManager> singletons;
	
	public static EntityManager getInstance(String entityName) throws Exception{
		EntityManager singleton = null;
		
		if(singletons == null){
			singletons = new HashMap<String, EntityManager>();
		}
		singleton = singletons.get(entityName);
		if(singleton == null){
			try{
				ClassPathResource resource = new ClassPathResource("applicationContext.xml");
				XmlBeanFactory factory = new XmlBeanFactory(resource);
				EntityManagerFactory emf = (EntityManagerFactory)factory.getBean(entityName);
				singleton = emf.createEntityManager();
				singletons.put(entityName, singleton);
			}catch(Exception ex)
			{
				throw ex;
			}
		}
		return singleton;
	}
	
	private EntityManagerHolder(String entityName){
		
	}
}
